#include <raw_api.h>
#include <stdio.h>
#include <lib_string.h>
#include <rsh.h>
#include <rsh_command.h>

#if (CONFIG_RAW_SYSTEM_STATISTICS > 0)


static RAW_S32 rsh_cpu_usuage_command(RAW_S8 *pcWriteBuffer, size_t xWriteBufferLen, const RAW_S8 *pcCommandString)
{
	LIST *iter;
	LIST *iter_temp;
	
	RAW_TASK_OBJ *task_iter;
	RAW_SYS_TIME_TYPE total_system_running_time = 0;
	RAW_U32 task_cpu_usuage = 0;
	
	iter = raw_task_debug.task_head.next;
	
	/*do it until list pointer is back to the original position*/ 
	while (iter != &(raw_task_debug.task_head)) {

		iter_temp  = iter->next;
		task_iter = raw_list_entry(iter, RAW_TASK_OBJ, task_debug_list);
		total_system_running_time += task_iter->task_time_total_run;
	
		/*move to list next*/
		iter = iter_temp;
	}


	iter = raw_task_debug.task_head.next;
	
	/*do it until list pointer is back to the original position*/ 
	while (iter != &(raw_task_debug.task_head)) {

		iter_temp  = iter->next;
		task_iter = raw_list_entry(iter, RAW_TASK_OBJ, task_debug_list);

		if (task_iter->task_time_total_run < 0xffffffffu) {
			task_cpu_usuage = (RAW_U32)((task_iter->task_time_total_run * 10000) / total_system_running_time);
		}
		
		else {

			task_cpu_usuage = (RAW_U32)((task_iter->task_time_total_run) / (total_system_running_time / 10000));
		}
		
		RAW_PORT_PRINTF("\r\ntask name is %s task cpu usuage is %d", task_iter->task_name, task_cpu_usuage );	
		
		/*move to list next*/
		iter = iter_temp;
	}

	
	
	return 1;
}


static xCommandLineInputListItem cpu_usuage_item;

static const xCommandLineInput cpu_usuage_cmd = 
{
	"stat",
	"stat -- show all task cpu usuage\n",
	rsh_cpu_usuage_command,
	0
};


void register_task_cpu_command(void)
{
	rsh_register_command(&cpu_usuage_cmd, &cpu_usuage_item);
}


#endif


